﻿using System;
using System.Web;
using HibernatingRhinos.Profiler.Appender.NHibernate;
using NHibernate.Cfg;
using NHibernate.Context;

namespace NhibernateDemoMvc
{
    public class Global : HttpApplication
    {
        protected void Application_Start(object sender, EventArgs e)
        {
            NHibernateProfiler.Initialize();
            var configuration = new Configuration().Configure();
            SessionFactoryAccessor.Set(configuration.BuildSessionFactory());
        }

        protected void Application_End(object sender, EventArgs e)
        {
            SessionFactoryAccessor.Factory.Dispose();
        }

        public Global()
        {
            BeginRequest += OpenNewSession;
            EndRequest += DisposeOfSession;
        }

        private static void OpenNewSession(object sender, EventArgs e)
        {
            var factory = SessionFactoryAccessor.Factory;
            CurrentSessionContext.Bind(factory.OpenSession());
        }

        private static void DisposeOfSession(object sender, EventArgs e)
        {
            var factory = SessionFactoryAccessor.Factory;
            CurrentSessionContext.Unbind(factory).Dispose();
        }
    }

}